﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class MyPanel : BasePanel
{
    public Image avatarImage;

    public Text nick;

    public Text desc;

    public Button logoutBtn;


    public Button chatListBtn;
    public Button friendListBtn;
    public Button myBtn;


    // Use this for initialization
    void Start()
    {
        //按钮事件函数绑定
        logoutBtn.onClick.AddListener(delegate { LogoutButtonClicked(); });

        chatListBtn.onClick.AddListener(delegate { ChatListButtonClicked(); });
        friendListBtn.onClick.AddListener(delegate { FriendListButtonClicked(); });
        myBtn.onClick.AddListener(delegate { MyButtonClicked(); });
    }

    // Update is called once per frame
    void Update()
    {
    }
    
    /// <summary>
    /// 更新组件显示
    /// </summary>
    public void SyncShow()
    {
        nick.text = UnityFacade.Instance.ApplicationManager.ActiveUser.Nick;
        desc.text = "个人介绍：xxxx";
        //获取头像并回显
        HttpTool.Instance.GetImageConvertToSpriteByURL(UnityFacade.Instance.ApplicationManager.ActiveUser.Avatar,"local");
        StartCoroutine(SetSpriteToImage());



    }
    
    private void ChatListButtonClicked()
    {
        UnityFacade.Instance.UiManager.PopPanel();

        UnityFacade.Instance.UiManager.PushPanel(PanelType.ChatListPanel);
    }


    private void FriendListButtonClicked()
    {
        UnityFacade.Instance.UiManager.PopPanel();

        UnityFacade.Instance.UiManager.PushPanel(PanelType.FriendListPanel);
    }


    private void MyButtonClicked()
    {
        SyncShow();
    }

    private void LogoutButtonClicked()
    {
        Debug.Log("注销了");
    }


    public override void OnEnter()
    {
        if (this.gameObject.activeSelf == false)
        {
            this.gameObject.SetActive(true);
        }
        //每次打开都需要更新一下最新的信息（从ApplicationManager取得）【ApplicationManager的User更新在必要时发起请求】
        SyncShow();
    }

    public override void OnPause()
    {
    }

    public override void OnResume()
    {
    }

    public override void OnExit()
    {
        this.gameObject.SetActive(false);
    }
    
    private IEnumerator SetSpriteToImage()
    {
        //todo 可以开启一个等待动画的显示
        
        while (HttpTool.Instance.LocalSprite == null)
        {
            yield return new WaitForFixedUpdate();
        }
        avatarImage.sprite = HttpTool.Instance.LocalSprite;
        //置为null，待下一次处理
        HttpTool.Instance.ClearSprite("local");
       
    }
    
}